package com.ca.singlesignon.utils;

import com.ca.singlesignon.config.RedisPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
/**
 * Create By Gary
 * 单点登录存储信息的redis工具类
 */
@Slf4j
@Component
public class RedisPoolUtil {

    @Autowired
    private RedisPool redisPool;

    //redis set方法
    public  String set(String key,String value){
        Jedis jedis=null;
        String result=null;
        try {
            jedis=redisPool.getJedis();
            result=jedis.set(key,value);
        } catch (Exception e) {
             log.error("set key:{} value:{} error",key,value,e);
            redisPool.returnBrokenResource(jedis);
             return result;
        }
        redisPool.returnResource(jedis);
        return result;
    }

    //redis set redis 过期方法,exTime 时间秒
    public  String setEx(String key,String value,int exTime){
        Jedis jedis=null;
        String result=null;

        try {
            jedis=redisPool.getJedis();
            result=jedis.setex(key,exTime,value);
        } catch (Exception e) {
             log.error("set key:{} value:{} error",key,value,e);
            redisPool.returnBrokenResource(jedis);
             return result;
        }
        redisPool.returnResource(jedis);
        return result;
    }

    //redis reset redis 有效期 方法,exTime 时间秒
    public  Long expire(String key,int exTime){
        Jedis jedis=null;
        Long result=null;

        try {
            jedis=redisPool.getJedis();
            result=jedis.expire(key,exTime);
        } catch (Exception e) {
             log.error("set key:{} error",key,e);
            redisPool.returnBrokenResource(jedis);
             return result;
        }
        redisPool.returnResource(jedis);
        return result;
    }

    //redis get方法
    public  String get(String key){
        Jedis jedis=null;
        String result=null;
        try {
            jedis=redisPool.getJedis();
            result=jedis.get(key);
        } catch (Exception e) {
             log.error("set key:{} error",key,e);
            redisPool.returnBrokenResource(jedis);
             return result;
        }
        redisPool.returnResource(jedis);
        return result;
    }

    //redis del方法
    public  Long del(String key){
        Jedis jedis=null;
        Long result=null;
        try {
            jedis=redisPool.getJedis();
            result=jedis.del(key);
        } catch (Exception e) {
             log.error("set key:{} error",key,e);
            redisPool.returnBrokenResource(jedis);
             return result;
        }
        redisPool.returnResource(jedis);
        return result;
    }
}
